package org.dut.community.controller;

import com.alibaba.fastjson2.JSONObject;
import org.dut.community.entity.Message;
import org.dut.community.entity.Page;
import org.dut.community.entity.User;
import org.dut.community.service.MessageService;
import org.dut.community.service.UserService;
import org.dut.community.util.CommunityConstant;
import org.dut.community.util.CommunityUtil;
import org.dut.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

@Controller
public class MessageController implements CommunityConstant {
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private HostHolder hostHolder;

    /**
     * 获取会话列表
     */
    @RequestMapping(path = "/letter/list",method = RequestMethod.GET)
    public String getLetterList(Model model, Page page){
        User user = hostHolder.getUser();
        // 分页信息
        page.setLimit(5);
        page.setPath("/letter/list");
        page.setRows(messageService.findConversationCount(user.getId()));

        // 会话列表
        List<Message> conversationList = messageService.
                findConversations(user.getId(),page.getOffset(),page.getLimit());

        // 封装 未读消息、消息总数等信息
        List<Map<String, Object>> conversations = new ArrayList<>();
        if(conversationList != null && !conversationList.isEmpty()){
            for (Message message : conversationList) {
                Map<String, Object> map = new HashMap<>();
                // 会话（最新私信）
                map.put("conversation", message);
                // 私信总数量
                map.put("letterCount",messageService.findLetterCount(message.getConversationId()));
                // 未读消息数量（单个会话）
                map.put("unreadCount",messageService.findLetterUnreadCount(user.getId(),
                        message.getConversationId()));
                // 目标用户id，用于显示头像
                map.put("target", getLetterTarget(message.getConversationId()));
                conversations.add(map);
            }
        }
        model.addAttribute("conversations", conversations);
        // 未读消息总数
        model.addAttribute("letterUnReadCount",
                messageService.findLetterUnreadCount(user.getId(),null));
        // 通知总数
        model.addAttribute("noticeUnReadCount",
                messageService.findNoticeUnreadCount(user.getId(),null));

        return "/site/letter";
    }

    /**
     * 通知列表
     */
    @RequestMapping(path = "/notice/list",method = RequestMethod.GET)
    public String getNoticeList(Model model){
        User user = hostHolder.getUser();

        // comment
        Message message = messageService.findLatestNotice(user.getId(),TOPIC_COMMENT);
        Map<String,Object> messageVO = new HashMap<>();
        if(message != null){
            messageVO.put("message",message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String,Object> data = JSONObject.parseObject(content,Map.class);
            messageVO.put("user",userService.findUserById((Integer) data.get("userId")));
            messageVO.put("entityType",data.get("entityType"));
            messageVO.put("entityId",data.get("entityId"));
            messageVO.put("postId",data.get("postId"));

            int count = messageService.findNoticeCount(user.getId(),TOPIC_COMMENT);
            messageVO.put("count",count);
            count = messageService.findNoticeUnreadCount(user.getId(),TOPIC_COMMENT);
            messageVO.put("unreadCount",count);

            model.addAttribute("commentNotice",messageVO);
        }

        // like
        message = messageService.findLatestNotice(user.getId(), TOPIC_LIKE);
        messageVO = new HashMap<>();
        if(message != null){
            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
            messageVO.put("user", userService.findUserById((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_LIKE);
            messageVO.put("count", count);
            count = messageService.findNoticeUnreadCount(user.getId(), TOPIC_LIKE);
            messageVO.put("unread", count);

            model.addAttribute("likeNotice", messageVO);
        }

        // follow
        message = messageService.findLatestNotice(user.getId(), TOPIC_FOLLOW);
        messageVO = new HashMap<>();
        if(message != null){
            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
            messageVO.put("user", userService.findUserById((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_FOLLOW);
            messageVO.put("count", count);
            count = messageService.findNoticeUnreadCount(user.getId(), TOPIC_FOLLOW);
            messageVO.put("unread", count);

            model.addAttribute("followNotice", messageVO);
        }

        // 未读消息总数
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(),null);
        model.addAttribute("letterUnreadCount",letterUnreadCount);
        // 未读通知总数
        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(),null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);

        return "/site/notice";
    }

    @RequestMapping(path = "/notice/detail/{topic}",method = RequestMethod.GET)
    public String getNoticeDetail(@PathVariable("topic")String topic,Page page,Model model) {
        User user = hostHolder.getUser();

        // 分页信息
        page.setLimit(5);
        page.setPath("/notice/detail/"+topic);
        page.setRows(messageService.findNoticeCount(user.getId(),topic));

        List<Message> noticeList = messageService.findNotices(user.getId(),topic,page.getOffset(),page.getLimit());
        List<Map<String,Object>> noticeVOList = new ArrayList<>();
        if(noticeList != null && !noticeList.isEmpty()){
            for (Message notice : noticeList) {
                Map<String,Object> map = new HashMap<>();
                map.put("notice",notice);
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String,Object> data = JSONObject.parseObject(content,Map.class);
                map.put("user",userService.findUserById((Integer) data.get("userId")));
                map.put("entityType",data.get("entityType"));
                map.put("entityId",data.get("entityId"));
                map.put("fromUser",userService.findUserById(notice.getFromId()));
                map.put("postId", data.get("postId"));

                noticeVOList.add(map);
            }
        }
        model.addAttribute("notices", noticeVOList);
        List<Integer> ids = getUnreadLetterIds(noticeList);
        if(!ids.isEmpty()){
            messageService.readMessage(ids);
        }
        return "/site/notice-detail";
    }

    /**
     * 私信详情
     */
    @RequestMapping(path = "/letter/detail/{conversationId}",method = RequestMethod.GET)
    public String getLetterDetail(@PathVariable("conversationId") String conversationId, Model model,Page page){
        page.setLimit(5);
        page.setPath("/letter/detail/"+conversationId);
        page.setRows(messageService.findLetterCount(conversationId));

        // 和某个用户的私信信息
        List<Message> letterList = messageService.findLetters(conversationId, page.getOffset(), page.getLimit());
        // 更新消息已读
        List<Integer> ids = getUnreadLetterIds(letterList);
        if(!ids.isEmpty()){
            messageService.readMessage(ids);
        }
        List<Map<String, Object>> letters = new ArrayList<>();
        if(letterList != null && !letterList.isEmpty()){
            for (Message message : letterList) {
                Map<String, Object> map = new HashMap<>();
                map.put("letter", message);
                map.put("fromUser", userService.findUserById(message.getFromId()));

                letters.add(map);
            }
        }
        model.addAttribute("letters", letters);
        model.addAttribute("target",getLetterTarget(conversationId));

        return "/site/letter-detail";
    }

    @RequestMapping(path = "/letter/send",method = RequestMethod.POST)
    @ResponseBody
    public String sendLetter(String toName, String content){
        User target = userService.findUserByName(toName);
        if(target == null){
            return CommunityUtil.getJSONString(400,"目标用户不存在！");
        }
        if(content==null || content.isEmpty()){
            return CommunityUtil.getJSONString(400,"私信内容不能为空！");
        }

        Message message = getMessage(content, target);
        messageService.addMessage(message);

        return CommunityUtil.getJSONString(0);
    }



    private Message getMessage(String content, User target) {
        Message message = new Message();
        message.setContent(content);
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(target.getId());
        // 会话id，始终让fromId < toId , 确保会话一致
        if(message.getFromId() < message.getToId()){
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        }else{
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }
        message.setStatus(0);
        message.setCreateTime(new Date());
        return message;
    }
    /**
     * 获取私信列表中 未读消息 的id
     */
    private List<Integer> getUnreadLetterIds(List<Message> letterList){
        List<Integer> ids = new ArrayList<>();
        if(letterList != null && !letterList.isEmpty()){
            for (Message message : letterList) {
                if(hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0){
                    ids.add(message.getId());
                }
            }
        }
        return ids;
    }
    private User getLetterTarget(String conversationId) {
        String[] ids = conversationId.split("_");
        int id1 = Integer.parseInt(ids[0]);
        int id2 = Integer.parseInt(ids[1]);

        if(hostHolder.getUser().getId() == id1){
            return userService.findUserById(id2);
        }else{
            return userService.findUserById(id1);
        }
    }


}
